package com.wrox.begjsp.ch27.wsproxy;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.moviejukebox.rottentomatoes.RottenTomatoes;
import com.moviejukebox.rottentomatoes.model.Link;
import com.moviejukebox.rottentomatoes.model.Movie;
import com.wrox.begjsp.ch27.dto.InterestItem;

public class MovieProvider implements WebserviceStore {
	/* The developer token from rotten tomatoes */
	private final static String rottenTomatoesApiKey = "y8zmruhzhbb87w2xq7gfyrtn";
	private RottenTomatoes rottenTomatoes;

	public MovieProvider() {
		this.rottenTomatoes = new RottenTomatoes(rottenTomatoesApiKey);
	}

	public Set<Movie> moviesSearch(String movieName) {
		return this.rottenTomatoes.moviesSearch(movieName);
	}

	@Override
	public InterestItem[] searchByKeyword(String keyword)
			throws RemoteException {
		List<InterestItem> resultList = new ArrayList<InterestItem>();
		for (Movie movie : moviesSearch(keyword)) {
			InterestItem item = new InterestItem();
			item.setItemName(movie.getTitle());
			Iterator<Link> it = movie.getLinks().iterator();
			while (it.hasNext()) {
				Link current = it.next();
				if (current.getLinkType().equalsIgnoreCase("alternate")) {
					item.setItemUrl(current.getLinkUrl());
					break;
				}
			}
			if (item.getItemUrl() == null){
				item.setItemUrl("http://google.com");
			}
			it = movie.getArtwork().iterator();
			if (it.hasNext()) {
				item.setImageUrl(it.next().getLinkUrl());
			}
			resultList.add(item);
		}
		return resultList.toArray(new InterestItem[resultList.size()]);
	}
}
